import React, { Component } from 'react'
import { Card, Table, Tag, Button, Modal, Typography, message, Tooltip } from 'antd';
import { getArtical, deleteArticalRequest } from '../../request'
import moment from 'moment'
import XLSX from 'xlsx'

const titleDisplayMap = {
    id: '编号',
    title: '标题',
    author: '作者',
    amount: '阅读量',
    createAt: '创建时间'
}

export default class index extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataSource: [],
            columns: [],
            total: 0,
            loading: true,
            offset: 0,
            limited: 10,
            deleteArticalTitle: '',
            isShowArticalModel: false,
            currentDelID:'',
            delConfirmLoading: false
        }
    }
    
    showDeleteArticalModel = (arg) => {
        // Modal.confirm({
        //     title: '操作不可逆，请三思',
        //     content: <Typography>确定要删除<span style={{color: 'red'}}>{arg.title}</span> 吗？</Typography>,
        //     okText: '确定',
        //     cancelText: '取消'
        // })
        this.setState({
            deleteArticalTitle: arg.title,
            isShowArticalModel: true,
            currentDelID:arg.id
        })
    }

    toEdit = (id) => {
        this.props.history.push(`/admin/artical/edit/${id}`)
        // this.props.history.push({
        //     pathname: `/admin/artical/${record.id}`,
        //     state:record.title
        // })
    }

    deleteArtical = () => {
        this.setState({
            delConfirmLoading: true
        })
        deleteArticalRequest(this.state.currentDelID)
        .then(res=>message.success(res.msg))
        .catch((err)=>message.error(err))
        .finally(()=>{
            this.setState({
                delConfirmLoading: false,
                isShowArticalModel: false
            },()=>{
                this.getData()
            })
        })
        
    }

    createColumn = (arg) => {
        
        const columns = arg.map(item=>{
            if(item === 'amount') {
                return  {
                    title: titleDisplayMap[item],
                    key: item,
                    render: (text, record) => {
                        const { amount} = record
                        return <Tooltip title={amount>222? `超过了222`:  `低于222`}>
                            <Tag color={amount>222? 'blue': 'red'}>{amount}</Tag>
                        </Tooltip>

                    }
                  }
            }
            if(item === 'createAt') {
                return  {
                    title: titleDisplayMap[item],
                    key: item,
                    render: (text, record) => {
                        const { createAt } = record
                        return moment(createAt).format("YYYY年MM月DD日")
                    }
                  }
            } 
            return {
                 title: titleDisplayMap[item],
                 dataIndex: item,
                 key: item,
               }
         })
         columns.push({
             title: '操作',
             key: 'action',
             render: (record) => {
                return <Button.Group>
                    <Button type='primary' onClick={this.toEdit.bind(this, record.id)} size='small'>编辑</Button>
                    <Button type='danger' onClick={this.showDeleteArticalModel.bind(this, record.id)} size='small'>删除</Button>
                </Button.Group>
             }
         })
        return columns;
    }
    hideModel = () => {
        this.setState({
            isShowArticalModel: false
        })
    }

    toExportExl = () => {
        const data = [];
            data[0] = []
      this.state.columns.forEach(item=>{
          data[0].push(item.title)
      })
      this.state.dataSource.forEach(item=>{
          item.createAt = moment(item.createAt).format("YYYY年MM月DD日")
          data.push(Object.values(item))
      })
      const xs = XLSX.utils.aoa_to_sheet(data)
      const wb = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(wb,xs, 'SheetJS')
      XLSX.writeFile(wb, `artical-${moment().format('YYYYMMDDHHmmss')}.xlsx`)
    }
    
    onPageChage = (page, pageSize) => {
        this.setState({
            offset: pageSize*(page - 1),
            limited: pageSize
        }, () => {
            this.getData()
        })
    }
    getData = () => {
        getArtical(this.state.offset, this.state.offset).then((res)=>{
            const columnKey = Object.keys(res.list[0])
            const columns = this.createColumn(columnKey)
            if (!this.updater.isMounted(this)) return;  // 如果请求完成之后组件已经销毁，就不要设置state以免报错
            this.setState({
                columns,
                total: res.total,
                dataSource: res.list
            })
        }).catch((err)=>{
            console.log(err)
        }).finally((err)=>{
            if (!this.updater.isMounted(this)) return;
            this.setState({
                loading: false
            })
        })
    }

    componentDidMount() {
       this.getData()
        
    }
    render() {
        return (
            <Card title="Default size card" 
                extra={<Button onClick={this.toExportExl}>导出Excel</Button>} 
                bordered={false}
                
                >
            <Table 
                dataSource={this.state.dataSource}
                columns={this.state.columns}
                rowKey={record=>record.id}
                pagination={{
                    total: this.state.total,
                    hideOnSinglePage: true,
                    onChange: this.onPageChage,
                    showSizeChanger: true,
                    showQuickJumper: true

                }}
                loading={this.state.loading}
                
                />;
                <Modal
                    title='操作不可逆，请三思'
                    visible={this.state.isShowArticalModel}
                    onCancel={this.hideModel}
                    onOk={this.deleteArtical} 
                    confirmLoading={this.state.delConfirmLoading}
                >
                    <Typography>确定要删除<span style={{color: 'red'}}>{this.state.deleteArticalTitle}</span> 吗？</Typography>    
                </Modal>
            </Card>
        )
    }
}
